package com.ruoyi.web.controller.mqtt;

import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
//import com.ruoyi.web.controller.dll.ZhenshiSdk;
import com.ruoyi.web.controller.dll.ZhenshiSdk;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.messaging.MessageHandler;
import org.springframework.stereotype.Component;

import java.util.Objects;

import static com.ruoyi.web.controller.mqtt.MqttConfig.CHANNEL_NAME_IN;

/**
 * @author hwf
 */
@Component
@AllArgsConstructor
public class MqttReceiver {

    private final MqttSender mqttSender;
    private final MqttProperties mqttProperties;

    @Bean
    @ServiceActivator(inputChannel = CHANNEL_NAME_IN)
    public MessageHandler handler() {
        return message -> {

            String topic = "topic/response/pos/" + mqttProperties.getPosId();
            String requestTopic = Objects.requireNonNull(message.getHeaders().get("mqtt_receivedTopic")).toString();
//            String responseTopic = requestTopic.replace("request", "response");
            StaticLog.info("收到的消息:{}", message.getPayload());
            String input = (String) message.getPayload();
            Request req = JSONUtil.toBean(input, Request.class);

            if (requestTopic.contains("response")) {
                String msgId = req.getMId();
                if (DefaultFuture.contains(msgId)) {
                    Response m = new Response();
                    m.setData(req.getData());
                    m.setMsg(req.getMsg());
                    DefaultFuture.received(msgId, m);
                }
            }

            if (requestTopic.contains("request")) {
                byte[] tmpstr = new byte[2048];

                int iret = ZhenshiSdk.lpr.bankall(Convert.toStr(req.getData()), tmpstr);
                Response reqs = new Response();
                reqs.setMId(req.getMId());
                reqs.setData(tmpstr);
                reqs.setMsg(String.valueOf(iret));
                mqttSender.sendWithTopicAndQos(topic, 0, JSONUtil.toJsonStr(reqs));
                StaticLog.info("回复的指令=>{}=>{}", topic, JSONUtil.toJsonStr(reqs));
            }

        };
    }


}
